<?php
$section = 'product';
$titre = _LB_PRODUCT_MANAGEMENT;
$smarty->assign("titre", $titre);

//get object ID
$id = Request::getIntNumber('id');
$act = Request::getIntNumber('act');

//get back link
$backlink = Session::getBackLink($section,"list/?");

$product = new Product();
if($id)
{
	if(!$product->getDetail($id))
		redirect($backlink);
}

$auto_increase = Request::getIntNumber('auto_increase');
$cats = Category::getTree();

//if action = UPDATE or CREATE
if ($act == ACT_VALID_EDIT)
{
	$product->NAME = trim(Request::get('NAME'));
	$product->SHORT_DESCRIPTION = trim($_POST['SHORT_DESCRIPTION']);
	$product->DESCRIPTION = trim($_POST['DESCRIPTION']);
	$product->POS = Request::getNumber('POS');
	$product->ID_CATEGORY = Request::getNumber('ID_CATEGORY');
    $product->DISABLED = Request::getNumber('DISABLED');

	if ($product->validateInput())
	{
		$product->save();

		foreach ($product->product_images as $product_image) {
			if ($product_image->REMOVED) {				
				$product_image->delete();
				continue;
			}
			$product_image->ID_PRODUCT = $product->ID;
			$product_image->save();
		}
		
		foreach ($product->product_downloads as $product_download) {
			if ($product_download->REMOVED) {				
				$product_download->delete();
				continue;
			}
			$product_download->ID_PRODUCT = $product->ID;
			$product_download->save();
		}

		foreach ($product->product_infos as $product_info) {
			if ($product_info->REMOVED) {				
				$product_info->delete();
				continue;
			}
			$product_info->ID_PRODUCT = $product->ID;
			$product_info->save();
		}
		redirect($backlink);
	}
}

include_once CKEDITOR_BASE_DIR. "ckeditor.php";
$CKEditor = new CKEditor();
$CKEditor->basePath = CKEDITOR_BASE_PATH;
$CKEditor->config['height'] = 300;
$CKEditor->config['filebrowserBrowseUrl'] = CKFINDER_BASE_PATH.'ckfinder.html';
$CKEditor->config['filebrowserImageBrowseUrl'] = CKFINDER_BASE_PATH.'ckfinder.html?type=Images';
$CKEditor->config['filebrowserFlashBrowseUrl'] = CKFINDER_BASE_PATH.'ckfinder.html?type=Flash';
$CKEditor->config['filebrowserUploadUrl'] = CKFINDER_BASE_PATH.'core/connector/php/connector.php?command=QuickUpload&type=Files';
$CKEditor->config['filebrowserImageUploadUrl'] = CKFINDER_BASE_PATH.'core/connector/php/connector.php?command=QuickUpload&type=Images';
$CKEditor->config['filebrowserFlashUploadUrl'] = CKFINDER_BASE_PATH.'core/connector/php/connector.php?command=QuickUpload&type=Flash';
//create cfer
$cfer = new Cfer(array(
	_LB_ACCUEIL => Utils::getHomeLink(),
	_LB_PRODUCT_MANAGEMENT => $backlink,
	($id == 0? _LB_ADD_PRODUCT : _LB_EDIT_PRODUCT) => Utils::getCurrentLink() ));

//if validate is false, display form again
$smarty->assign('cfer', $cfer);
$smarty->assign('act', $act);
$smarty->assign('product', $product);
$smarty->assign('auto_increase', $auto_increase);
$smarty->assign('cats', $cats);
$smarty->assign('backlink', $backlink);
$smarty->assign('CKEditor', $CKEditor);
$smarty->display('product_form.html');
